package com.example.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 指定允许的前端地址（不能用 *）
        corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:5173")); // Vue 默认端口
        corsConfiguration.setAllowCredentials(true); // 允许携带 cookie / token
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader("*"); // 可选：暴露所有响应头

        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}